#include "client.h"
#include <QDebug>

Client::Client(std::string addr, short portMS, short portGS) : _addr(addr), _portMainServ(portMS), _portGameServ(portGS)
{
    isConnectedMain = true;
    isConnectedGame = true;
    sf::Uint8 connectedMain = 0, connectedGame = 0;

    while (connectedMain != 1 || connectedGame != 1)
    {
        getPseudo();

        if (DEBUG) {std::cout << "connexion au serveur main ..." << std::endl;}

        if (_sockMainServ.connect(_addr, _portMainServ) != sf::Socket::Done)
        {
            QMessageBox::critical(NULL, "Erreur", "Connexion au serveur principal impossible - port principal");
            isConnectedMain = false;
        }

        if(isConnectedMain)
        {
            if (DEBUG) {std::cout << "connecte (main)" << std::endl;}

            sf::Packet p;
            p << _pseudo.toStdString();
            send(p, true);
            p.clear();
            recv(p, true);
            p >> connectedMain;
        }

        if (DEBUG) {std::cout << "connexion au serveur game ..." << std::endl;}

        if(!isConnectedMain || _sockGameServ.connect(_addr, _portGameServ) != sf::Socket::Done)
        {
            QMessageBox::critical(NULL, "Erreur", "Connexion au serveur principal impossible - port partie");
            isConnectedGame = false;
        }

        if(isConnectedGame)
        {
            if (DEBUG) {std::cout << "connecte (game)" << std::endl;}

            sf::Packet p;
            p << _pseudo.toStdString();
            send(p, false);
            p.clear();
            recv(p, false);
            p >> connectedGame;
        }

        if((isConnectedMain && isConnectedGame) && (connectedMain != 1 || connectedGame != 1))
        {
            QMessageBox::critical(NULL, "Erreur", "Pseudo deja utilise");
            _sockMainServ.disconnect();
            _sockGameServ.disconnect();
        }

        if(!isConnectedMain || !isConnectedGame)
        {
            connectedMain = 1;
            connectedGame = 1;
        }
    }

    _selector.add(_sockGameServ);
    _selector.add(_sockMainServ);
}

void Client::send(sf::Packet & p, bool MainServ)
{
    if(MainServ && isConnectedMain)
        _sockMainServ.send(p);
    else if (!MainServ && isConnectedGame)
        _sockGameServ.send(p);
}

void Client::recv(sf::Packet & p, bool MainServ)
{
    if(MainServ && isConnectedMain)
        _sockMainServ.receive(p);
    else if(!MainServ  && isConnectedGame)
        _sockGameServ.receive(p);
}

void Client::getPseudo()
{
    bool ok = false;
    _pseudo = QInputDialog::getText(NULL, QString("Pseudo"), QString("Rentrez votre pseudo"), QLineEdit::Normal, QString(), &ok);

    if (!ok || _pseudo.isEmpty())
    {
        getPseudo();
    }
}
